package com.moxiao.yfjh.module.member.service.auth;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import com.moxiao.yfjh.framework.common.enums.CommonStatusEnum;
import com.moxiao.yfjh.framework.common.enums.UserTypeEnum;
import com.moxiao.yfjh.framework.common.exception.ServiceException;
import com.moxiao.yfjh.framework.common.exception.enums.GlobalErrorCodeConstants;
import com.moxiao.yfjh.framework.common.util.monitor.TracerUtils;
import com.moxiao.yfjh.framework.common.util.servlet.ServletUtils;
import com.moxiao.yfjh.module.member.controller.app.auth.vo.*;
import com.moxiao.yfjh.module.member.controller.app.auth.vo.AppAuthLoginReqVO;
import com.moxiao.yfjh.module.member.controller.app.auth.vo.AppAuthLoginRespVO;
import com.moxiao.yfjh.module.member.controller.app.auth.vo.AppAuthSmsLoginReqVO;
import com.moxiao.yfjh.module.member.controller.app.auth.vo.AppAuthSmsSendReqVO;
import com.moxiao.yfjh.module.member.controller.app.auth.vo.AppAuthSmsValidateReqVO;
import com.moxiao.yfjh.module.member.controller.app.auth.vo.AppAuthSocialLoginReqVO;
import com.moxiao.yfjh.module.member.controller.app.auth.vo.AppAuthWeixinMiniAppLoginReqVO;
import com.moxiao.yfjh.module.member.convert.auth.AuthConvert;
import com.moxiao.yfjh.module.member.dal.dataobject.user.MemberUserDO;
import com.moxiao.yfjh.module.member.service.user.MemberUserService;
import com.moxiao.yfjh.module.system.api.logger.LoginLogApi;
import com.moxiao.yfjh.module.system.api.logger.dto.LoginLogCreateReqDTO;
import com.moxiao.yfjh.module.system.api.oauth2.OAuth2TokenApi;
import com.moxiao.yfjh.module.system.api.oauth2.dto.OAuth2AccessTokenCreateReqDTO;
import com.moxiao.yfjh.module.system.api.oauth2.dto.OAuth2AccessTokenRespDTO;
import com.moxiao.yfjh.module.system.api.social.SocialUserApi;
import com.moxiao.yfjh.module.system.api.social.dto.SocialUserBindReqDTO;
import com.moxiao.yfjh.module.system.api.social.dto.SocialUserRespDTO;
import com.moxiao.yfjh.module.system.enums.logger.LoginLogTypeEnum;
import com.moxiao.yfjh.module.system.enums.logger.LoginResultEnum;
import com.moxiao.yfjh.module.system.enums.oauth2.OAuth2ClientConstants;
import com.moxiao.yfjh.module.system.enums.sms.SmsSceneEnum;
import com.moxiao.yfjh.module.system.enums.social.SocialTypeEnum;
import com.moxiao.yfjh.module.system.sms.utils.AlyISmsUtils;
import com.alibaba.fastjson.JSONObject;
import com.moxiao.yfjh.module.member.enums.ErrorCodeConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import static com.moxiao.yfjh.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.moxiao.yfjh.framework.common.util.servlet.ServletUtils.getClientIP;

/**
 * 会员的认证 Service 接口
 *
 * @author mx
 */
@Service
@Slf4j
public class MemberAuthServiceImpl implements MemberAuthService {

    private final static String smsSendKey = "SMS_CODE";
    @Resource
    private MemberUserService userService;

    @Resource
    private AlyISmsUtils alyISmsUtils;

    @Resource
    private LoginLogApi loginLogApi;
    @Resource
    private SocialUserApi socialUserApi;
    @Resource
    private OAuth2TokenApi oauth2TokenApi;

    @Resource
    private WxMaService wxMaService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public AppAuthLoginRespVO login(AppAuthLoginReqVO reqVO) {
        // 使用手机 + 密码，进行登录。
        MemberUserDO user = login0(reqVO.getMobile(), reqVO.getPassword());

        // 如果 socialType 非空，说明需要绑定社交用户
        String openid = null;
        if (reqVO.getSocialType() != null) {
            openid = socialUserApi.bindSocialUser(new SocialUserBindReqDTO(user.getId(), getUserType().getValue(),
                    reqVO.getSocialType(), reqVO.getSocialCode(), reqVO.getSocialState()));
        }

        // 创建 Token 令牌，记录登录日志
        return createTokenAfterLoginSuccess(user, reqVO.getMobile(), LoginLogTypeEnum.LOGIN_MOBILE, openid);
    }

    @Override
    @Transactional
    public AppAuthLoginRespVO smsLogin(AppAuthSmsLoginReqVO reqVO) {
        // 校验验证码
        String userIp = getClientIP();

        String redisKey = smsSendKey + reqVO.getMobile();
        String s = stringRedisTemplate.opsForValue().get(redisKey);
        //校验验证码
        Assert.notNull(Objects.equals(reqVO.getCode(),s), "获取验证码失败");

        // 获得获得注册用户
        MemberUserDO user = userService.createUserIfAbsent(reqVO.getMobile(), userIp);
        Assert.notNull(user, "获取用户失败，结果为空");

        // 如果 socialType 非空，说明需要绑定社交用户
        String openid = null;
        if (reqVO.getSocialType() != null) {
            openid = socialUserApi.bindSocialUser(new SocialUserBindReqDTO(user.getId(), getUserType().getValue(),
                    reqVO.getSocialType(), reqVO.getSocialCode(), reqVO.getSocialState()));
        }

        // 创建 Token 令牌，记录登录日志
        return createTokenAfterLoginSuccess(user, reqVO.getMobile(), LoginLogTypeEnum.LOGIN_SMS, openid);
    }

    @Override
    public AppAuthLoginRespVO socialLogin(AppAuthSocialLoginReqVO reqVO) {
        // 使用 code 授权码，进行登录。然后，获得到绑定的用户编号
        SocialUserRespDTO socialUser = socialUserApi.getSocialUser(UserTypeEnum.MEMBER.getValue(), reqVO.getType(),
                reqVO.getCode(), reqVO.getState());
        if (socialUser == null) {
            throw com.moxiao.yfjh.framework.common.exception.util.ServiceExceptionUtil.exception(
                    ErrorCodeConstants.AUTH_THIRD_LOGIN_NOT_BIND);
        }

        // 自动登录
        MemberUserDO user = userService.getUser(socialUser.getUserId());
        if (user == null) {
            throw com.moxiao.yfjh.framework.common.exception.util.ServiceExceptionUtil.exception(
                    ErrorCodeConstants.USER_NOT_EXISTS);
        }

        // 创建 Token 令牌，记录登录日志
        return createTokenAfterLoginSuccess(user, user.getMobile(), LoginLogTypeEnum.LOGIN_SOCIAL, socialUser.getOpenid());
    }

    @Override
    public AppAuthLoginRespVO weixinMiniAppLogin(AppAuthWeixinMiniAppLoginReqVO reqVO) {
        // 获得对应的手机号信息
        // TODO @芋艿：需要弱化微信小程序的依赖，通过 system 获取手机号
        WxMaPhoneNumberInfo phoneNumberInfo;
        try {
            phoneNumberInfo = wxMaService.getUserService().getPhoneNoInfo(reqVO.getPhoneCode());
        } catch (Exception exception) {
            throw com.moxiao.yfjh.framework.common.exception.util.ServiceExceptionUtil.exception(
                    ErrorCodeConstants.AUTH_WEIXIN_MINI_APP_PHONE_CODE_ERROR);
        }
        // 获得获得注册用户
        MemberUserDO user = userService.createUserIfAbsent(phoneNumberInfo.getPurePhoneNumber(), getClientIP());
        Assert.notNull(user, "获取用户失败，结果为空");

        // 绑定社交用户
        String openid = socialUserApi.bindSocialUser(new SocialUserBindReqDTO(user.getId(), getUserType().getValue(),
                SocialTypeEnum.WECHAT_MINI_APP.getType(), reqVO.getLoginCode(), ""));

        // 创建 Token 令牌，记录登录日志
        return createTokenAfterLoginSuccess(user, user.getMobile(), LoginLogTypeEnum.LOGIN_SOCIAL, openid);
    }

    private AppAuthLoginRespVO createTokenAfterLoginSuccess(MemberUserDO user, String mobile,
                                                            LoginLogTypeEnum logType, String openid) {
        // 插入登陆日志
        createLoginLog(user.getId(), mobile, logType, LoginResultEnum.SUCCESS);
        // 创建 Token 令牌
        OAuth2AccessTokenRespDTO accessTokenRespDTO = oauth2TokenApi.createAccessToken(new OAuth2AccessTokenCreateReqDTO()
                .setUserId(user.getId()).setUserType(getUserType().getValue())
                .setClientId(OAuth2ClientConstants.CLIENT_ID_DEFAULT));
        // 构建返回结果
        return AuthConvert.INSTANCE.convert(accessTokenRespDTO, openid);
    }

    @Override
    public String getSocialAuthorizeUrl(Integer type, String redirectUri) {
        return socialUserApi.getAuthorizeUrl(type, redirectUri);
    }

    private MemberUserDO login0(String mobile, String password) {
        final LoginLogTypeEnum logTypeEnum = LoginLogTypeEnum.LOGIN_MOBILE;
        // 校验账号是否存在
        MemberUserDO user = userService.getUserByMobile(mobile);
        if (user == null) {
            createLoginLog(null, mobile, logTypeEnum, LoginResultEnum.BAD_CREDENTIALS);
            throw com.moxiao.yfjh.framework.common.exception.util.ServiceExceptionUtil.exception(
                    ErrorCodeConstants.AUTH_LOGIN_BAD_CREDENTIALS);
        }
        if (!userService.isPasswordMatch(password, user.getPassword())) {
            createLoginLog(user.getId(), mobile, logTypeEnum, LoginResultEnum.BAD_CREDENTIALS);
            throw com.moxiao.yfjh.framework.common.exception.util.ServiceExceptionUtil.exception(
                    ErrorCodeConstants.AUTH_LOGIN_BAD_CREDENTIALS);
        }
        // 校验是否禁用
        if (ObjectUtil.notEqual(user.getStatus(), CommonStatusEnum.ENABLE.getStatus())) {
            createLoginLog(user.getId(), mobile, logTypeEnum, LoginResultEnum.USER_DISABLED);
            throw com.moxiao.yfjh.framework.common.exception.util.ServiceExceptionUtil.exception(
                    ErrorCodeConstants.AUTH_LOGIN_USER_DISABLED);
        }
        return user;
    }

    private void createLoginLog(Long userId, String mobile, LoginLogTypeEnum logType, LoginResultEnum loginResult) {
        // 插入登录日志
        LoginLogCreateReqDTO reqDTO = new LoginLogCreateReqDTO();
        reqDTO.setLogType(logType.getType());
        reqDTO.setTraceId(TracerUtils.getTraceId());
        reqDTO.setUserId(userId);
        reqDTO.setUserType(getUserType().getValue());
        reqDTO.setUsername(mobile);
        reqDTO.setUserAgent(ServletUtils.getUserAgent());
        reqDTO.setUserIp(getClientIP());
        reqDTO.setResult(loginResult.getResult());
        loginLogApi.createLoginLog(reqDTO);
        // 更新最后登录时间
        if (userId != null && Objects.equals(LoginResultEnum.SUCCESS.getResult(), loginResult.getResult())) {
            userService.updateUserLogin(userId, getClientIP());
        }
    }

    @Override
    public void logout(String token) {
        // 删除访问令牌
        OAuth2AccessTokenRespDTO accessTokenRespDTO = oauth2TokenApi.removeAccessToken(token);
        if (accessTokenRespDTO == null) {
            return;
        }
        // 删除成功，则记录登出日志
        createLogoutLog(accessTokenRespDTO.getUserId());
    }

    @Override
    public void sendSmsCode(Long userId, AppAuthSmsSendReqVO reqVO) {
        // 情况 1：如果是修改手机场景，需要校验新手机号是否已经注册，说明不能使用该手机了
        if (Objects.equals(reqVO.getScene(), SmsSceneEnum.MEMBER_UPDATE_MOBILE.getScene())) {
            MemberUserDO user = userService.getUserByMobile(reqVO.getMobile());
            if (user != null && !Objects.equals(user.getId(), userId)) {
                throw com.moxiao.yfjh.framework.common.exception.util.ServiceExceptionUtil.exception(
                        ErrorCodeConstants.AUTH_MOBILE_USED);
            }
        }
        // 情况 2：如果是重置密码场景，需要校验手机号是存在的
        if (Objects.equals(reqVO.getScene(), SmsSceneEnum.MEMBER_RESET_PASSWORD.getScene())) {
            MemberUserDO  user= userService.getUserByMobile(reqVO.getMobile());
            if (user == null) {
                throw com.moxiao.yfjh.framework.common.exception.util.ServiceExceptionUtil.exception(
                        ErrorCodeConstants.USER_MOBILE_NOT_EXISTS);
            }
        }
// todo 验证码生成临时注释
//        Integer code = (int) ((Math.random() * 9 + 1) * 100000);
        Integer code = 1234;
        Map<String, String> params = new HashMap<>();
        params.put("code", String.valueOf(code));
        params.put("minutes", "5");

        // 执行发送
        JSONObject jsonObject = alyISmsUtils.sendSms(reqVO.getMobile(), JSONObject.toJSONString(params));

//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("code","200");
        jsonObject.put("code",code);
        if (Objects.nonNull(jsonObject) && Objects.equals(jsonObject.getString("code"),"200")){
            //存到redis
            String redisKey = smsSendKey + reqVO.getMobile();
            stringRedisTemplate.opsForValue().set(redisKey, String.valueOf(code), 5, TimeUnit.SECONDS);
        }

    }

    @Override
    public void validateSmsCode(Long userId, AppAuthSmsValidateReqVO reqVO) {
        String redisKey = smsSendKey + reqVO.getMobile();
        String s = stringRedisTemplate.opsForValue().get(redisKey);
        //校验验证码
        if (Objects.equals(reqVO.getCode(),s)){
           return;
        }
        throw new ServiceException(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(), "验证码不存在");
    }

    @Override
    public AppAuthLoginRespVO refreshToken(String refreshToken) {
        OAuth2AccessTokenRespDTO accessTokenDO = oauth2TokenApi.refreshAccessToken(refreshToken,
                OAuth2ClientConstants.CLIENT_ID_DEFAULT);
        return AuthConvert.INSTANCE.convert(accessTokenDO, null);
    }

    private void createLogoutLog(Long userId) {
        LoginLogCreateReqDTO reqDTO = new LoginLogCreateReqDTO();
        reqDTO.setLogType(LoginLogTypeEnum.LOGOUT_SELF.getType());
        reqDTO.setTraceId(TracerUtils.getTraceId());
        reqDTO.setUserId(userId);
        reqDTO.setUserType(getUserType().getValue());
        reqDTO.setUsername(getMobile(userId));
        reqDTO.setUserAgent(ServletUtils.getUserAgent());
        reqDTO.setUserIp(getClientIP());
        reqDTO.setResult(LoginResultEnum.SUCCESS.getResult());
        loginLogApi.createLoginLog(reqDTO);
    }

    private String getMobile(Long userId) {
        if (userId == null) {
            return null;
        }
        MemberUserDO user = userService.getUser(userId);
        return user != null ? user.getMobile() : null;
    }

    private UserTypeEnum getUserType() {
        return UserTypeEnum.MEMBER;
    }

}
